package com.stx.action;

import java.text.SimpleDateFormat;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.stx.entity.User;
import com.stx.service.impl.UserServiceImpl;
import com.stx.util.MD5_Test;

public class UserJson extends ActionSupport {

	private UserServiceImpl us;
	private User user = null;
	private String date;
	private String email;
	private String password;
    private String message;
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public User getUser() {
		return user;
	}

	public String getDate() {
		return date;
	}

	public String getEmail() {
		return email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public void setUs(UserServiceImpl us) {
		this.us = us;
	}

	public UserServiceImpl getUs() {
		return us;
	}

	public void setUser(User user) {
		this.user = user;
	}

	/*
	 * 更新用户的操作 首先判断下是否用户修改了email 如果更换邮箱先检查下是否被使用
	 */
	public String upadteUser() {
		User u = (User) ServletActionContext.getRequest().getSession()
				.getAttribute("user");
		/* 检查下session是否有效 */
		if (u != null) {
			user.setUs_password(u.getUs_password());
			user.setUs_email(email);
			user.setUs_id(u.getUs_id());
			user.setUs_image(u.getUs_image());
		} else {
			message="请重新登陆！";
			return "sessionerror";
		}
		/* 判断是否邮箱被修改了 */
		if (!email.equals(u.getUs_email()) && (us.getUser(user).size() != 0)) {
			message="此邮箱已被使用了";
			return "failure";
		} else {
			us.updateUser(user);
			message="信息修改成功";
			/*
			 * 重新得打user然胡重置session
			 */
			user = us.findUser(user).get(0);
			ServletActionContext.getRequest().getSession()
					.setAttribute("user", user);
			return "success";
		}
	}

	/*
	 * 修改用户的密码 首先检查原始密码是否正确
	 */
	public String updatePassword() {
        System.out.println(password);
		User u = (User) ServletActionContext.getRequest().getSession()
				.getAttribute("user");
		/* 检查下session是否有效 */
		if (u != null) {
			user.setUs_nickname(u.getUs_nickname());
			user.setUs_email(u.getUs_email());
			user.setUs_image(u.getUs_image());
			user.setUs_id(u.getUs_id());
		} else {
			message="请重新登陆！";
			return "sessionerror";
		}
		/* 比对下密码是否输入有误 */
		password=MD5_Test.MD5(password);
		if (!u.getUs_password().equals(password)) {
			message="密码输入错误";
			return "failure";
		} else {
			user.setUs_password(MD5_Test.MD5(user.getUs_password()));
			us.updateUser(user);
			message="密码修改成功";
			user = us.findUser(user).get(0);
			ServletActionContext.getRequest().getSession()
					.setAttribute("user", user);
			return "success";
		}
	}
}
